<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="家庭名称" prop="familyId" style="width: 350px;">
        <el-select
            v-model="queryParams.familyId"
            placeholder="请选择家庭"
            clearable
            filterable
            @change="handleFamilyChange"
            @keyup.enter="handleQuery"
        >
          <el-option
              v-for="item in familyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="房间名称" prop="roomId" style="width: 350px;">
        <el-select
            v-model="queryParams.roomId"
            placeholder="请选择房间"
            clearable
            filterable
            @keyup.enter="handleQuery"
        >
          <el-option
              v-for="item in filteredRoomOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="设备类型" prop="deviceName" style="width: 350px;">
        <el-select v-model="queryParams.deviceName" placeholder="请选择设备类型" clearable>
          <el-option
              v-for="dict in device_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="安装日期" prop="installationDate">
        <el-date-picker clearable
                        v-model="queryParams.installationDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择安装日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['airsystem:devices:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['airsystem:devices:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['airsystem:devices:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="devicesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
          label="序号"
          align="center"
          width="80"
          class-name="serial-number"
      >
        <template #default="scope">
    <span class="serial">
      {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
    </span>
        </template>
      </el-table-column>
<!--      <el-table-column label="设备ID" align="center" prop="deviceId" />-->
      <el-table-column label="房间信息" align="center">
        <template #default="scope">
          <div class="room-info">
            <span class="family-name">{{ scope.row._familyName }}</span>
            <span class="separator">/</span>
            <span class="room-name">{{ scope.row._roomName }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="设备类型" align="center" prop="deviceName">
        <template #default="scope">
          <dict-tag :options="device_type" :value="scope.row.deviceName"/>
        </template>
      </el-table-column>
      <el-table-column label="安装日期" align="center" prop="installationDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.installationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['airsystem:devices:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['airsystem:devices:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改设备管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="devicesRef" :model="form" :rules="rules" label-width="80px">
        <!-- 新增家庭选择 -->
        <el-form-item label="家庭名称" prop="familyId">
          <el-select
              v-model="form.familyId"
              placeholder="请先选择家庭"
              clearable
              filterable
              @change="handleDialogFamilyChange"
          >
            <el-option
                v-for="item in familyOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 修改房间选择 -->
        <el-form-item label="房间名称" prop="roomId">
          <el-select
              v-model="form.roomId"
              placeholder="请选择房间"
              clearable
              filterable
              :disabled="!form.familyId"
          >
            <el-option
                v-for="item in filteredDialogRoomOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceName">
          <el-select v-model="form.deviceName" placeholder="请选择设备类型">
            <el-option
                v-for="dict in device_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="安装日期" prop="installationDate">
          <el-date-picker clearable
                          v-model="form.installationDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择安装日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Devices">
import {listDevices, getDevices, delDevices, addDevices, updateDevices} from "@/api/airsystem/devices";
import {listRooms} from "@/api/airsystem/rooms";
import {listFamilies} from "@/api/airsystem/families";
import {getCurrentInstance, ref, reactive, toRefs, onMounted, computed} from 'vue';

const {proxy} = getCurrentInstance();
const {device_type} = proxy.useDict('device_type');

const devicesList = ref([]);
const roomOptions = ref([]);
const familyOptions = ref([]);

const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    familyId: null,
    roomId: null,
    deviceName: null,
    installationDate: null
  },
  rules: {
    familyId: [
      {required: true, message: "必须选择所属家庭", trigger: "blur"}
    ],
    roomId: [
      {required: true, message: "必须选择房间", trigger: "blur"}
    ],
    deviceName: [
      {required: true, message: "设备类型不能为空", trigger: "change"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询房间列表 */
function getRoomList() {
  listRooms().then(response => {
    roomOptions.value = response.rows.map(item => ({
      value: item.roomId,
      label: item.roomName,
      familyId: item.familyId
    }));
  });
}

/** 根据 roomId 获取房间名称 */
const getRoomName = (roomId) => {
  const room = roomOptions.value.find(item => item.value === roomId);
  return room ? room.label : '未知房间';
};

/** 查询家庭列表 */
function getFamilyList() {
  listFamilies().then(response => {
    familyOptions.value = response.rows.map(item => ({
      value: item.familyId,
      label: item.familyName
    }));
  });
}

/** 过滤房间选项 */
const filteredRoomOptions = computed(() => {
  if (!queryParams.value.familyId) return [];
  return roomOptions.value.filter(room => room.familyId === queryParams.value.familyId);
});

/** 过滤对话框中的房间选项 */
const filteredDialogRoomOptions = computed(() => {
  if (!form.value.familyId) return [];
  return roomOptions.value.filter(room => room.familyId === form.value.familyId);
});

/** 处理家庭选择变化 */
const handleFamilyChange = () => {
  queryParams.value.roomId = null; // 清空已选房间
  handleQuery(); // 更新查询结果
};

/** 处理对话框中的家庭选择变化 */
const handleDialogFamilyChange = () => {
  form.value.roomId = null; // 清空已选房间
};

/** 查询设备管理列表 */
function getList() {
  loading.value = true;
  listDevices(queryParams.value).then(response => {
    let rawData = response.rows;
    let filteredData = rawData.filter(device => {
      const room = roomOptions.value.find(r => r.value === device.roomId);
      const familyFilter = queryParams.value.familyId
          ? room?.familyId === queryParams.value.familyId
          : true;
      const roomFilter = queryParams.value.roomId
          ? device.roomId === queryParams.value.roomId
          : true;

      return familyFilter && roomFilter;
    });

    devicesList.value = filteredData.map(device => {
      const room = roomOptions.value.find(r => r.value === device.roomId);
      const family = familyOptions.value.find(f => f.value === room?.familyId);
      return {
        ...device,
        _familyName: family?.label || '未知家庭',
        _roomName: room?.label || '未知房间',
        _originalRoomId: device.roomId
      };
    });

    total.value = devicesList.value.length;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    deviceId: null,
    roomId: null,
    deviceName: null,
    installationDate: null
  };
  proxy.resetForm("devicesRef");
}

// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置按钮操作
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.deviceId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

// 新增按钮操作
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加设备管理";
}

// 修改按钮操作
function handleUpdate(row) {
  reset();
  const _deviceId = row.deviceId || ids.value;
  getDevices(_deviceId).then(response => {
    form.value = response.data;

    const matchedRoom = roomOptions.value.find(r => r.value === form.value.roomId);
    form.value.familyId = matchedRoom?.familyId || null;

    open.value = true;
    title.value = "修改设备管理";
  });
}

// 提交按钮
function submitForm() {
  proxy.$refs["devicesRef"].validate(valid => {
    if (valid) {
      if (form.value.deviceId != null) {
        updateDevices(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDevices(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

// 删除按钮操作
function handleDelete(row) {
  const _deviceIds = row.deviceId || ids.value;
  proxy.$modal.confirm('是否确认删除设备管理编号为"' + _deviceIds + '"的数据项？').then(function () {
    return delDevices(_deviceIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

onMounted(() => {
  getRoomList();
  getFamilyList();
  getList();
});
</script>



